﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using SLS.Base;
using SLS.DataBase;
using SLS.ExClassLib.Database;
using SLS.ExClassLib.DataType;
using SLS.ExClassLib.Message;
using SLS.Document;
namespace SLS.ExClassLib.Data
{
    public partial class ExDataRow
    { 
        private SLQDBSET SetQuery
        {
            get
            {
                return DataAccessService.Instance.setQueryCond;
            }
        }
        private SLDBSET SetGlobal
        {
            get
            {
                return DataAccessService.Instance.setGlobal;
            }
        }
        public void AddSet2Create(string TBName, DataTable tbThis, bool blCreated = true)
        {
            try
            {
                if (tbThis != null)
                {
                    Set2Create.Merge(tbThis);
                }
                Table2Create t2c;
                var query = from Table2Create t2cl in Table2CreateList
                            where t2cl.TBName == TBName
                            select t2cl;
                if (query.Count() == 0)
                {
                    t2c = new Table2Create(TBName, blCreated);
                    Table2CreateList.Add(t2c);
                }
                else
                {
                    foreach (Table2Create t2cl in query)
                    {
                        t2cl.blCreated = blCreated;
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public ExDataRow GetExDataRow(DataRow dwThis, bool Add, bool CheckDataQuality = false, bool IsUpdateData = false)
        {
            ExDataRow row = null;
            try
            {
                string INSTANCEID = dwThis["INSTANCEID"].ToString();
                var query = from ExDataRow datalist in DataList
                            where datalist.INSTANCEID == INSTANCEID
                            select datalist;
                foreach (ExDataRow exdw in query)
                {
                    if (IsUpdateData)
                    {
                        exdw.Item.ItemArray = dwThis.ItemArray;
                    }
                    row = exdw;
                }
                if (row == null
                    && Add)
                {
                    row = new ExDataRow(dwThis, CheckDataQuality);
                    DataList.Add(row);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return row;
        }
        public DataSet BuildSet2Create(bool IsCreate)
        {
            DataSet setReturn = null;
            try
            {
                getSet2Create();
                CheckingSet2Create(IsCreate);
                setReturn = this.Set2Create;
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public DataSet OnSaveRecord(int level)
        {
            DataSet setEvent = new DataSet();
            DataSet setReturn = new DataSet();
            try
            {
                MessageEx msg = new MessageEx();
                msg.JobID = "OnSaveRecord";
                switch (level)
                {
                    case 1:
                        setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, Item);
                        break;
                    case 2:
                        setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, Item);
                        setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwGoodsMasterKeyRelation);
                        break;
                    default:
                        break;
                }
                msg.setEvent = setEvent;
               setReturn.Merge(DataAccessService.Instance.QueryData(msg));
                foreach(DataRow dwTemp in setReturn.Tables[TBName].Rows)
                {
                    if (dwTemp["INSTANCEID"].ToString() == INSTANCEID)
                        Item.ItemArray = dwTemp.ItemArray;
                }
                if (setReturn.Tables.Contains("GoodsMasterKeyRelation"))
                {
                    foreach (DataRow dwTemp in setReturn.Tables["GoodsMasterKeyRelation"].Rows)
                    {
                        dwGoodsMasterKeyRelation = dwTemp;
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public virtual DataSet MergeUI_Model_Data(DataRow dwReference, DataRow dwModel, List<string> ForeignKeyList, List<string> PrimaryKeyList, DataSet set4Reference)
        {
            DataRow dwTarget = null;
            DataSet setReturn = new DataSet();
            DataSet setResult = new DataSet();
            string TBName = dwReference.Table.TableName;
            try
            {
                //1st, 保留参考数据传递过来的信息，一般是主键信息。只要字段名相同就复制。
                //dwTarget = DataAccessService.Instance.MapDataRow("", "", TBName, dwReference, null, null, false);
                if (TBName.Contains("QueryCond"))
                {
                    dwTarget = SetQuery.Tables[TBName].NewRow();
                }
                else
                {
                    dwTarget = SetGlobal.Tables[TBName].NewRow();
                }
                DataAccessService.Instance.MapDataRow(ref dwTarget, dwReference, false);
                dwTarget["SM"] = dwReference["SM"];
                dwTarget["INSTANCEID"] = Guid.NewGuid().ToString().ToUpper();
                //2.根据指定的字段，将主键字段进一步扩展填充。有些字段名不同，但是也要借助这个个规则，进行复制数据。
                DataAccessService.Instance.MapDataRow(ref dwTarget, dwReference, ForeignKeyList, PrimaryKeyList, true);
                //3.根据相同列表，将模板数据进行映射。
                DataAccessService.Instance.MapDataRow(ref dwTarget, dwModel, ForeignKeyList, PrimaryKeyList, true);
                DataAccessService.Instance.ImportDataTable(ref setReturn, dwTarget);
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public ExDataSet QueryAndCreateData(DataSet set2Query, DataRow dwThis, DataSet set4Ref = null)
        {
            MessageEx msg = new MessageEx();
            ExDataSet setReturn = null;
            if (set2Query.Tables.Count == 0)
                return setReturn;
            string tbName = "";
            string querycond = "";
            foreach (DataTable tbTemp in set2Query.Tables)
            {
                if (tbTemp.TableName.Contains("QueryCond"))
                {
                    tbName = tbTemp.TableName.Replace("QueryCond", "");
                    querycond = tbTemp.TableName;
                }
            }
            if (tbName == "")
                return setReturn;

            setReturn = new ExDataSet(tbName);
            DataSet setResult = null;
            DataSet setModel = new DataSet();
            DataRow dwQueryCond = set2Query.Tables[querycond].Rows[0];
            DataRow dwReference = DataAccessService.Instance.MapDataRow("", "", tbName, dwQueryCond, null, null, true);
            string QueryType = dwQueryCond["QUERYTYPE"].ToString().Trim();

            msg.JobID = "OnQuery" + tbName;
            msg.setEvent = set2Query;
            setResult = DataAccessService.Instance.QueryData(msg);
            setReturn.Merge(setResult);
            if (QueryType == "QueryOnly")
            {
                return setReturn;
            }
            if (setResult.Tables[tbName].Rows.Count > 0)
            {
                return setReturn;
            }
            dwQueryCond["SUBSTATUS"] = "AUTO";
            //20121002
            //SLBC doc;
            //string DocType = "Edit" + tbName;
            //doc = DocumentManagement.Instance.OpenDocument(DocType, "HomeDocumentUI", "TAB_MAIN", "ExTabControl");
            setResult = CreateDataRow(dwQueryCond, set2Query, set4Ref);
            setReturn.Merge(setResult);
            return setReturn;
        }
        public int GetMaxIDSysKeyData(string TBName, string KeyCondition)
        {
            DataSet setRequest;
            DataRow dwQueryCond = null, dwSysKeyData;
            ExDataSet setReturn;
            int newValue = 1;
            int StepSize = 1;

            try
            {
                #region Get the MaxID
                setRequest = new DataSet();
                setRequest.DataSetName = "SysKeyDataQueryCond";
                dwQueryCond = DataAccessService.Instance.setQueryCond.SysKeyDataQueryCond.NewRow();
                dwQueryCond["QUERYTYPE"] = "CreateByQuery";
                dwQueryCond["CONDTYPE"] = "IX_SysKeyData";
                dwQueryCond["SM"] = "1";
                dwQueryCond["KEYDEFTYPE"] = "1";
                dwQueryCond["GTPRE"] = "SS";
                dwQueryCond["GTKRY"] = "100032";
                dwQueryCond["CURRENTVALUE"] = "1";
                dwQueryCond["STEPSIZE"] = "1";
                dwQueryCond["MAXVALUE"] = "999999999";
                dwQueryCond["GDKEY"] = KeyCondition;
                dwQueryCond["KEYCONDITION"] = KeyCondition;
                dwQueryCond["KEYNAME"] = KeyCondition;
                dwQueryCond["KEYDES"] = KeyCondition;
                dwQueryCond["LDES"] = KeyCondition;
                dwQueryCond["SDES"] = KeyCondition;
                setRequest = (DataSet)DataAccessService.Instance.ImportDataTable(setRequest, dwQueryCond);
                setReturn = QueryAndCreateData(setRequest, dwQueryCond);
                if (setReturn.Tables["SysKeyData"].Rows.Count == 0)
                {
                    dwSysKeyData = DataAccessService.Instance.setGlobal.SysKeyData.NewRow();
                    DataAccessService.Instance.MapDataRow(ref dwSysKeyData, dwQueryCond, true);
                }
                else
                {
                    dwSysKeyData = setReturn.Tables["SYSKEYDATA"].Rows[0];
                }
                StepSize = System.Convert.ToInt16(dwSysKeyData["STEPSIZE"]);
                newValue = System.Convert.ToInt16(dwSysKeyData["CURRENTVALUE"]) + StepSize;
                dwSysKeyData["CURRENTVALUE"] = newValue;
                #endregion
                #region Update the SysKeyData
                DataSet set2Save = new DataSet();
                set2Save = (DataSet)DataAccessService.Instance.ImportDataTable(set2Save, dwSysKeyData);
                MessageEx msgRequest = new MessageEx();
                msgRequest.JobID = "OnSaveRecord";
                msgRequest.setEvent = set2Save;
                msgRequest.Tag = "UpdateWhenExist";
                DataAccessService.Instance.QueryData(msgRequest);
                #endregion
            }
            catch (Exception ex)
            {
                throw;
            }
            return newValue;
        }
        public void BuildInstanceKey(ref DataRow dwThis, int PositionID, int Line = 0)
        {
            string InstanceKey = dwThis["INSTANCEKEY"].ToString().Trim();
            try
            {
                if (dwThis.Table.Columns.Contains("GDKEYID"))
                {
                    dwThis["GDKEYID"] = PositionID;
                }
                dwThis["POSITIONID"] = PositionID;
                InstanceKey += "." + PositionID;
                if (Line > 0)
                {
                    InstanceKey += "." + Line;
                }
                dwThis["INSTANCEKEY"] = InstanceKey;
                dwThis["SUBSTATUS"] = "New";
                dwThis["STATUS"] = "New";
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public DataRow UpdateLastPositionID(DataRow dwTarget, DataRow dwModel, string CreationSource = "AUTO")
        {
            DataRow dwQueryCond;
            string TBModelName;
            int LastPoisitionID = 0;
            int PoisitionID = 0;
            DataRow dwThis = null;
            DataSet setResult;
            string KeyCondition = "";
            DataSet setMsg;
            try
            {
                if (dwModel != null)
                {
                    TBModelName = dwModel.Table.TableName;
                    #region Update the Model's LastPoisitionID
                    KeyCondition = DataAccessService.Instance.GetPrimaryKeyValue(dwModel);
                    LastPoisitionID = GetMaxIDSysKeyData(TBModelName, KeyCondition);
                    dwModel["LASTPOSITIONID"] = LastPoisitionID;
                    string QueryType = "QueryOnly";
                    string CondtionType = "DB_" + TBModelName + "_UPDATE_BY_INSTANCEID";
                    string TBQueryCond = TBModelName + "QueryCond";
                    dwQueryCond = DataAccessService.Instance.MapDataRow(QueryType, CondtionType, TBQueryCond, dwModel, null, null, true);
                    ExDataSet setReturn = new ExDataSet();
                    setMsg = new DataSet();
                    setMsg = (DataSet)DataAccessService.Instance.ImportDataTable(setMsg, dwQueryCond);
                    setMsg.DataSetName = dwQueryCond.Table.TableName;
                    setResult = QueryAndCreateData(setMsg, dwThis);
                    #endregion
                    #region Update the the new records' PoisitionID
                    dwTarget["CREATIONSOURCE"] = CreationSource;
                    dwTarget["LASTPOSITIONID"] = 1;
                    PoisitionID = System.Convert.ToInt16(dwModel["POSITIONID"].ToString());
                    dwTarget["INSTANCEKEY"] = dwModel["INSTANCEKEY"].ToString().Trim() + "." + LastPoisitionID.ToString();
                    if (TBModelName == "GoodsTypeKeyDef")
                    {
                        PoisitionID = LastPoisitionID;
                        dwTarget["INSTANCEKEY"] = dwModel["INSTANCEKEY"];
                    }
                    #endregion
                    BuildInstanceKey(ref dwTarget, PoisitionID);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return dwTarget;
        }
        public virtual DataSet CreateDataRow(DataRow dwQueryCond, DataSet set2Query, DataSet set4Ref, bool blSave = true)
        {

            //dwTarget=dwGoodsType;
            DataSet setReturn = new DataSet();
            DataSet setModel = new DataSet();
            DataSet setResult;
            DataSet setMiddle = new DataSet();
            string TBName = dwQueryCond.Table.TableName.Replace("QueryCond", "");
            DataRow dwReference = DataAccessService.Instance.MapDataRow("", "", TBName, dwQueryCond, null, null, true);
            string CreationSource = dwQueryCond["CREATIONSOURCE"].ToString().Trim();

            List<string> KeyList = new List<string>();
            List<string> TKeyList = new List<string>();
            try
            {
                setModel = GetSetModel(dwQueryCond, set2Query, ref KeyList, ref TKeyList);
                if (setModel.Tables.Count == 0)
                {
                   return setReturn;
                }
                foreach (DataRow dwModel in setModel.Tables[0].Rows)
                {
                    setResult = MergeUI_Model_Data(dwReference, dwModel, KeyList, TKeyList, set4Ref);
                    foreach (DataRow dwTemp in setResult.Tables[TBName].Rows)
                    {
                        UpdateLastPositionID(dwTemp, dwModel);
                    }
                    setMiddle.Merge(setResult);
                }
                if (blSave)
                {
                    MessageEx msg = new MessageEx();
                    msg.JobID = "OnSaveRecord";
                    msg.setEvent = setMiddle;
                    msg.Tag = "NotUpdateWhenExist";
                    setResult = DataAccessService.Instance.QueryData(msg);
                    setReturn.Merge(setResult);
                }
                //DocumentManagement.Instance.SendJobForProcessing(setMiddle, this, "Edit", false);
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public DataSet GetSetModel(DataRow dwQueryCond, DataSet set4Reference, ref List<string> KeyList, ref List<string> TKeyList)
        {
            ExDataSet setReturn = new ExDataSet();
            DataRow[] dwForeignKeyLists;
            string TBName = dwQueryCond.Table.TableName.Replace("QueryCond", "");
            DataRow dwReference = DataAccessService.Instance.MapDataRow("", "", TBName, dwQueryCond, null, null, true);
            DataSet set2Query = new DataSet();
            DataRow dwForeignKey = null;
            string TargetTable = "";
            string FKeyInstanceTable;
            string expression = "";
            try
            {
                FKeyInstanceTable = dwQueryCond["FKEYINSTANCETABLE"].ToString().Trim();
                #region===============When GoodsMasterProperty=================
                if (FKeyInstanceTable == "GoodsMasterProperty")
                {
                    expression = "TBNAME='" + TBName + "' and TTTABLE='GoodsMasterProperty' and TYPE='Model'";
                    dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                    if (dwForeignKeyLists.Count() > 0)
                    {
                        dwForeignKey = dwForeignKeyLists[0];
                    }
                    set2Query = GetQueryCondByForeignKey(ref KeyList, ref TKeyList, ref TargetTable, dwForeignKey, dwReference);
                    setReturn.Merge(set4Reference.Tables["GoodsMasterProperty"]);
                    return setReturn;
                }
                #endregion

                #region===============Else=================
                expression = "TBNAME='" + TBName + "' and TYPE='Model'";
                dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKey = dwForeignKeyLists[0];
                }
                set2Query = GetQueryCondByForeignKey(ref KeyList, ref TKeyList, ref TargetTable, dwForeignKey, dwReference);
                #endregion
                setReturn = QueryAndCreateData(set2Query, dwReference);
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public DataSet GenerateGoodsMasterKeyRelation(DataRow dwGDKEY)
        {
            DataSet setReturn = new DataSet();
            try
            {
                string SUBSTATUS = dwGDKEY["SUBSTATUS"].ToString().Trim();
                DataSet setRequest = new DataSet();
                MessageEx msg = new MessageEx();
                DataRow dwQueryCond = null;
                dwQueryCond = DataAccessService.Instance.setQueryCond.GoodsMasterKeyRelationQueryCond.NewRow();
                dwQueryCond["QUERYTYPE"] = "CreateByQuery";
                dwQueryCond["CONDTYPE"] = "IX_GoodsMasterKeyRelation_Key";
                dwQueryCond["SM"] = dwGDKEY["SM"];
                dwQueryCond["KREAL"] = dwGDKEY.Table.TableName;
                dwQueryCond["GTPRE"] = dwGDKEY["GTPRE"];
                dwQueryCond["GTKRY"] = dwGDKEY["GTKRY"];
                dwQueryCond["GDKEY"] = dwGDKEY["GDKEY"];
                dwQueryCond["LINE"] = 0;
                setRequest = (DataSet)DataAccessService.Instance.ImportDataTable(setRequest, dwQueryCond);
                setRequest.DataSetName = "GoodsMasterKeyRelationQueryCond";
                DataSet set4Ref = new DataSet();
                set4Ref = (DataSet)DataAccessService.Instance.ImportDataTable(set4Ref, dwGDKEY);
                setReturn = QueryAndCreateData(setRequest, dwQueryCond, set4Ref);
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public void OnCreateByQueryFinish(DataRow dwNew, DataRow dwSource)
        {
            try
            {
                DataRow dwQueryCond;
                MessageEx msg = new MessageEx();
                DataSet tnSet = new DataSet();
                DataSet setEvent = new DataSet();
                ExDataSet setReturn = new ExDataSet();
                string TBName = dwSource.Table.TableName;
                DataRow dwGoodsMasterKeyRelationOld = null;
                if (dwSource == null)
                    return;
                string GDKEY = dwSource["GDKEY"].ToString().Trim();
                string expression = "GDKEY='" + GDKEY + "'";
                DataRow[] dwTemps = Set5Property.Tables["GoodsMasterKeyRelation"].Select(expression);
                if (dwTemps.Count() > 0)
                {
                    dwGoodsMasterKeyRelationOld = dwTemps[0];
                }
                dwQueryCond = DataAccessService.Instance.MapDataRow("CreateByQuery", "IX_" + TBName, TBName + "QueryCond", null, dwNew, null, null);
                dwQueryCond["SUBSTATUS"] = "NewGoodsMasterKeyRelationComplete;";
                dwQueryCond["STATUS"] = "New;";
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwQueryCond);
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwSource);
                msg.setEvent = setEvent;
                setEvent.DataSetName = dwQueryCond.Table.TableName;
                setReturn = QueryAndCreateData(setEvent, dwQueryCond);

                foreach (DataTable tbTemp in setReturn.Tables)
                {
                    if (tbTemp.TableName == "GoodsMasterKeyRelation")
                    {
                        foreach (DataRow dwTemp in tbTemp.Rows)
                        {
                            if (dwTemp["MKEYINSTANCETABLE"].ToString().Trim() == "KeyBoardInput")
                                dwTemp["MGDKEY"] = "";
                            else
                            {
                                dwTemp["MGDKEY"] = dwGoodsMasterKeyRelationOld["MGDKEY"];
                            }
                            msg.JobID = "OnSaveRecord";
                            setEvent = new DataSet();
                            setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwTemp);
                            msg.setEvent = setEvent;
                            DataAccessService.Instance.QueryData(msg);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public DataRow GetCopyRow(ExDataRow dwThis)
        {
            DataRow row = dwThis.Item;
            DataRow dwNew = row.Table.NewRow();
            try
            {
                dwNew.ItemArray = row.ItemArray;
                if (dwNew.Table.Columns.Contains("INSTANCEID"))
                {
                    dwNew["INSTANCEID"] = Guid.NewGuid().ToString().ToUpper();
                }
                if (dwNew.Table.Columns.Contains("GDKEY"))
                {
                    dwNew["GDKEY"] = "1@2=1";
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return dwNew;
        }
        public DataSet DataSetConclusion(DataSet dsSource, string TBName)
        {
            DataSet dsConclusion = new DataSet();
            string TableQueryCond = "";
            try
            {
                int TotalRecord = dsSource.Tables[TBName].Rows.Count;
                var query = from dwBaseTable in dsSource.Tables[TBName].AsEnumerable()
                            where dwBaseTable["STATUS"].ToString().TrimEnd().ToUpper() == "COMPLETE"
                            select dwBaseTable;
                int CompleteRecord = query.Count();
                DataRow dwConclusion = SetGlobal.DataSetConclusion.NewDataSetConclusionRow();
                string Conclusion = "NORECORD";
                if (TotalRecord == CompleteRecord)
                {
                    if (TotalRecord > 0)
                        Conclusion = "TOTALCOMPLETE";
                }
                else
                {
                    Conclusion = "NOTCOMPLETE";
                }
                dwConclusion["SM"] = dsSource.Tables[TBName].Rows[0]["SM"];
                dwConclusion["TABLENAME"] = TBName;
                dwConclusion["TOTALRECORD"] = TotalRecord;
                dwConclusion["COMPLETERECORD"] = CompleteRecord;
                dwConclusion["CONCLUSION"] = Conclusion;

                dsConclusion = (DataSet)DataAccessService.Instance.ImportDataTable(dsConclusion, dwConclusion);
                TableQueryCond = TBName + "QueryCond";
                foreach (DataRow dwTemp in dsSource.Tables[TBName].Rows)
                {
                    //Selected Rows
                    dsConclusion = (DataSet)DataAccessService.Instance.ImportDataTable(dsConclusion, dwTemp);
                }
                DataRow dwTempQueryCond = Set5Property.Tables[TableQueryCond].Rows[0];
                dsConclusion = (DataSet)DataAccessService.Instance.ImportDataTable(dsConclusion, dwTempQueryCond);
                DataSet set2Save = new DataSet();
                foreach (DataTable tbTemp in dsSource.Tables)
                {
                    DataRow[] foundRows = tbTemp.Select("", "", DataViewRowState.ModifiedCurrent);
                    foreach (DataRow dwTemp in foundRows)
                    {
                        set2Save = (DataSet)DataAccessService.Instance.ImportDataTable(set2Save, dwTemp);
                    }
                }
                if (set2Save.Tables.Count > 0)
                {
                    MessageEx msgRequest = new MessageEx();
                    msgRequest.JobID = "OnSaveRecord";
                    msgRequest.setEvent = set2Save;
                    DataAccessService.Instance.QueryData(msgRequest);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return dsConclusion;
        }
        public DataSet DataSetConclusion()
        {
            DataSet dsConclusion = new DataSet();
            try
            {
                int TotalRecord = Set5Property.Tables[TBName].Rows.Count;
                var query = from dwBaseTable in Set5Property.Tables[TBName].AsEnumerable()
                            where dwBaseTable["STATUS"].ToString().TrimEnd().ToUpper() == "COMPLETE"
                            select dwBaseTable;
                int CompleteRecord = query.Count();
                DataRow dwConclusion = SetGlobal.DataSetConclusion.NewDataSetConclusionRow();
                string Conclusion = "NORECORD";
                if (TotalRecord == CompleteRecord)
                {
                    if (TotalRecord > 0)
                        Conclusion = "TOTALCOMPLETE";
                }
                else
                {
                    Conclusion = "NOTCOMPLETE";
                }
                dwConclusion["TABLENAME"] = TBName;
                dwConclusion["TOTALRECORD"] = TotalRecord;
                dwConclusion["COMPLETERECORD"] = CompleteRecord;
                dwConclusion["CONCLUSION"] = Conclusion;

                dsConclusion = (DataSet)DataAccessService.Instance.ImportDataTable(dsConclusion, dwConclusion);
            }
            catch (Exception ex)
            {
                throw;
            }
            return dsConclusion;
        }
        public DataRow PrepareQueryCond(string QueryType, string TForeignKey, string TableQueryCond, DataRow dwSource, Queue ForeignKeyList, Queue PrimaryKeyList)
        {
            //DataRow dwTarget = MapDataRow(QueryType, TForeignKey, TableQueryCond, dwSource, ForeignKeyList, PrimaryKeyList, true);
            DataRow dwTarget = DataAccessService.Instance.MapDataRow(QueryType, TForeignKey, TableQueryCond, dwSource, null, null, true);

            string GTKRY = "";
            if (dwSource.Table.Columns.Contains("GTKRY")
             && !dwSource.Table.TableName.Contains("GOODSTYPEKEYDEF"))
            {
                GTKRY = dwSource["GTKRY"].ToString().Trim();
                if (GTKRY == "")
                {
                    if (dwTarget.Table.Columns.Contains("KEYINSTANCETABLE"))
                    {
                        dwTarget["KEYINSTANCETABLE"] = dwSource.Table.TableName;
                    }
                }
            }
            return dwTarget;
        }
    
        public void OnDeleteRecord(ExDataRow dwThis)
        {
            try
            {
                DataSet setEvent = new DataSet();
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwThis.Item);
                MessageEx msg = new MessageEx();
                msg.JobID = "OnDeleteRecord";
                msg.setEvent = setEvent;
                DataAccessService.Instance.QueryData(msg);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void SaveActiveRecord(DataRow dwThis, MessageEx msg)
        {
            try
            {
                DataSet setEvent = new DataSet();
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwThis);
                MessageEx msgRequest = new MessageEx();
                msgRequest.JobID = "OnSaveRecord";
                msgRequest.setEvent = setEvent;
                DataAccessService.Instance.QueryData(msgRequest);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
        public void SaveActiveRecord(DataTable tbThis, MessageEx msg)
        {
            try
            {
                DataSet set2Save = new DataSet();
                set2Save.Merge(tbThis);
                MessageEx msgRequest = new MessageEx();
                msgRequest.JobID = "OnSaveRecord";
                msgRequest.setEvent = set2Save;
                DataAccessService.Instance.QueryData(msgRequest);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
        public void SaveActiveRecord(DataSet set2Save, MessageEx msg)
        {
            try
            {
                MessageEx msgRequest = new MessageEx();
                msgRequest.JobID = "OnSaveRecord";
                msgRequest.setEvent = set2Save;
                DataSet setResult = DataAccessService.Instance.QueryData(msgRequest);
                foreach (DataRow dwTemp in setResult.Tables[TBName].Rows)
                {
                    GetExDataRow(dwTemp, true);
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
        public DataSet GetQueryCond(DataRow dwForeignKeyList, DataRow dwThis, string CheckingType = "IsNull")
        {
            Dictionary<string, object> dicSource;
            #region================= Variable==================
            DataSet setReturn = new DataSet();
            string basetable = "";
            string ForeignKey = "";
            string QueryType = "";
            string TargetTable = "";
            string QueryCond;
            Queue TargetKeyList = new Queue();
            Queue SourceKeyList = new Queue();
            string TableName = "";
            #endregion
            try
            {
                #region Get Querycond
                ForeignKey = dwForeignKeyList["FOREIGNKEY"].ToString().Trim();
                if (CheckingType == "")
                {
                    CheckingType = dwForeignKeyList["CHECKINGTYPE"].ToString().Trim();
                }
                TableName = dwForeignKeyList["TABLENAME"].ToString().Trim();
                TargetTable = dwForeignKeyList["TARGETTABLE"].ToString().Trim();

                dicSource = new Dictionary<string, object>();
                dicSource = BuildKeyPair(dicSource, dwForeignKeyList, dwThis);
                SourceKeyList = (Queue)dicSource["SourceKeyList"];
                TargetKeyList = (Queue)dicSource["TargetKeyList"];
                QueryType = (string)dicSource["QueryType"];
                basetable = (string)dicSource["basetable"];
                QueryCond = (string)dicSource["QueryCond"];

                #endregion
                setReturn.DataSetName = basetable;
                DataRow dwBaseQuery = DataAccessService.Instance.MapDataRow(QueryType, QueryCond, basetable, null, dwThis, SourceKeyList, TargetKeyList);
                if (CheckingType == "IsNull")
                {
                    dwBaseQuery["QUERYTYPE"] = "QueryOnly";
                }
                setReturn = (DataSet)DataAccessService.Instance.ImportDataTable(setReturn, dwBaseQuery);
                #region
                /*if (TargetTable == "GoodsMasterAssemblePoint"
                  && CheckingType == "IsComplete"
                  )
                {
                    dwBaseQuery["Line"] = 1;
                    dwBaseQuery["Quantity"] = 1.00;
                    dwBaseQuery["SQuantity"] = 1.00;
                    setReturn.Merge(IncludeMGDKEY(dwThis));
                }
                */
                #endregion
            }
            catch (System.Exception ex)
            {
                throw;
            } 
            return setReturn;
        }
        private DataSet IncludeMGDKEY(DataRow dwGDKEY)
        {
            DataSet setReturn = new DataSet();
            DataSet setThis = Set5Property;
            try
            {
                string expression =
                    "SM='" + dwGDKEY["SM"].ToString() + "'"
                  + " and KEYINSTANCETABLE='" + dwGDKEY.Table.TableName + "'"
                  + " and KEYDEFTYPE='" + dwGDKEY["KEYDEFTYPE"].ToString() + "'"
                  + " and GOODSTYPEKEY='" + dwGDKEY["GTPRE"].ToString() + "'"
                  + " and GTKRY='" + dwGDKEY["GTKRY"].ToString() + "'"
                  + " and GDKEY='" + dwGDKEY["GDKEY"].ToString() + "'"
                    ;
                DataRow[] dwTemps = setThis.Tables["GoodsMasterKeyRelation"].Select(expression);
                DataRow dwGoodsMasterKeyRelation = null;
                DataRow dwMGDKEY = null;
                if (dwTemps.Count() > 0)
                {
                    dwGoodsMasterKeyRelation = dwTemps[0];
                }
                if (dwGoodsMasterKeyRelation != null)
                {
                    string MKeyinstanceTable = dwGoodsMasterKeyRelation["MKeyinstanceTable"].ToString().Trim();
                    if (MKeyinstanceTable != TBName)
                    {
                        expression =
                    "SM='" + dwGoodsMasterKeyRelation["SM"].ToString() + "'"
                     + " AND KEYDEFTYPE='" + dwGoodsMasterKeyRelation["MKEYDEFTYPE"].ToString() + "'"
                     + " AND GOODSTYPEKEY='" + dwGoodsMasterKeyRelation["MGOODSTYPEKEY"].ToString() + "'"
                     + " AND GTKRY='" + dwGoodsMasterKeyRelation["MGTKRY"].ToString() + "'"
                     + " AND GDKEY='" + dwGoodsMasterKeyRelation["MGDKEY"].ToString() + "'"
                       ;
                        dwTemps = setThis.Tables[MKeyinstanceTable].Select(expression);
                        if (dwTemps.Count() > 0)
                        {
                            dwMGDKEY = dwTemps[0];
                            setReturn = (DataSet)DataAccessService.Instance.ImportDataTable(setReturn, dwMGDKEY);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public List<string> GetSourceForeingKey(string TBName, string ForeignKey, DataRow dwForeignKey = null)
        {
            List<string> ListForeignKey = new List<string>();
            DataRow[] dwForeignKeyLists;
            string XKey;
            string expression;
            if (dwForeignKey == null)
            {
                expression = "TBNAME='" + TBName + "' and ForeignKey='" + ForeignKey + "'";
                dwForeignKeyLists =SetGlobal.FOREIGNKEYLIST.Select(expression);
                dwForeignKey = null;
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKey = dwForeignKeyLists[0];
                }
            }
            for (int i = 0; i <= 9; i++)
            {
                XKey = dwForeignKey["KEY" + i.ToString()].ToString().Trim();
                if (XKey != "")
                {
                    ListForeignKey.Add(XKey);
                }
            }

            return ListForeignKey;
        }
        public List<string> GetTargetForeingKey(string TBName, string ForeignKey, DataRow dwForeignKey = null)
        {
            List<string> ListForeignKey = new List<string>();
            DataRow[] dwForeignKeyLists;
            string XKey;
            string expression = "";
            if (dwForeignKey == null)
            {
                expression = "TBNAME='" + TBName + "' and FOREIGNKEY='" + ForeignKey + "'";
                dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                dwForeignKey = null;
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKey = dwForeignKeyLists[0];
                }
            }
            for (int i = 0; i <= 9; i++)
            {
                XKey = dwForeignKey["TKEY" + i.ToString()].ToString().Trim();
                if (XKey != "")
                {
                    ListForeignKey.Add(XKey);
                }
            }
            return ListForeignKey;
        }
        public List<string> GetAbsoluteGDKEY(string TBName, string ForeignKey, DataRow dwForeignKey = null)
        {
            List<string> ListForeignKey = new List<string>();
            DataRow[] dwForeignKeyLists;
            string XKey;
            string expression = "";

            if (dwForeignKey == null)
            {
                expression = "TBNAME='" + TBName + "' and FOREIGNKEY='PK_" + TBName + "' and TYPE='PrimaryKey'";
                dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                dwForeignKey = null;
                if (dwForeignKeyLists.Count() > 0)
                {
                    dwForeignKey = dwForeignKeyLists[0];
                }
            }
            for (int i = 0; i <= 9; i++)
            {
                XKey = dwForeignKey["KEY" + i.ToString()].ToString().Trim();
                if (XKey != "SM"
                    && XKey != "KEYDEFTYPE"
                    && XKey != "GTPRE"
                    && XKey != "GTKRY"
                    && XKey != ""
                    )
                {
                    ListForeignKey.Add(XKey);
                }
            }
            return ListForeignKey;
        }
        private DataSet ValidateByForeignKey(DataRow dwThis, DataRow[] dwForeignKeyLists, string CheckingType = "IsNull")
        {
            ExDataSet setReturn = new ExDataSet();
            DataSet setResult = null;
            string TargetTable = "";
            DataSet setTemp;
            string TBName = dwThis.Table.TableName;
            string TForeignKey = "";
            string ProcessTable = "";
            string SUBSTATUS = "";
            try
            {
                SUBSTATUS = dwThis["SUBSTATUS"].ToString().Trim();
                foreach (DataRow dwForeignKeyList in dwForeignKeyLists)
                {
                    TargetTable = dwForeignKeyList["TARGETTABLE"].ToString().Trim();
                    TForeignKey = dwForeignKeyList["TFOREIGNKEY"].ToString().Trim();
                    CheckingType = dwForeignKeyList["CHECKINGTYPE"].ToString().Trim();
                    setTemp = GetQueryCond(dwForeignKeyList, dwThis);
                    TBName = setTemp.DataSetName.Replace("QueryCond", "");
                    if (setTemp.Tables.Count == 0)
                        continue;
                    if (SUBSTATUS.Contains(TBName + "Complete;")
                     && CheckingType == "IsComplete"
                     )
                    {
                        CheckingType = "IsNull";
                    }
                    setResult = QueryAndCreateData(setTemp, dwThis);
                    setReturn.Merge(setResult);
                    if (CheckingType == "IsComplete"
                        && setResult.Tables.Contains(TBName)
                        && !SUBSTATUS.Contains(TBName + "Complete;"))
                    {
                        dwThis["SUBSTATUS"] = SUBSTATUS + TBName + "Complete;";
                        SUBSTATUS = dwThis["SUBSTATUS"].ToString().Trim();
                        SaveActiveRecord(dwThis, null);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public Dictionary<string, object> BuildKeyPair(Dictionary<string, object> dicSource, DataRow dwForeignKeyList, DataRow dwThis)
        {
            try
            {
                #region================= Variable=================
                string ForeignKey = dwForeignKeyList["ForeignKey"].ToString().Trim();
                string FCheckingType = dwForeignKeyList["CheckingType"].ToString().Trim();
                string FPrimaryKeyTable = dwForeignKeyList["TargetTable"].ToString().Trim();
                string ColumnName = "";
                string DtQueryCond = "";
                string QueryType = "";
                bool blConditions = true;
                Queue TargetKeyList = new Queue();
                Queue SourceKeyList = new Queue();
                string basetable = "";
                string CONDTYPE;
                string KeysTable;
                string SUBSTATUS = dwThis["SUBSTATUS"].ToString().Trim();
                #endregion

                #region===Build the exchanging Keylist TargetKeyList/SourceKeyList--
                string KeyI = "";
                for (int i = 0; i < 10; i++)
                {
                    KeyI = "TKey" + i.ToString();
                    ColumnName = dwForeignKeyList[KeyI].ToString().Trim();
                    if (ColumnName != "")
                    {
                        TargetKeyList.Enqueue(ColumnName);
                    }
                    KeyI = "Key" + i.ToString();
                    ColumnName = dwForeignKeyList[KeyI].ToString().Trim();
                    if (ColumnName != "")
                    {
                        if (ColumnName != "KeyInstanceTable")
                        {
                            blConditions = blConditions && dwThis[ColumnName].ToString().Trim() != "";
                        }
                        SourceKeyList.Enqueue(ColumnName);
                    }
                }
                #endregion

                #region QueryType, QueryTable
                KeysTable = FPrimaryKeyTable;
                DtQueryCond = KeysTable;
                QueryType = "QueryOnly";
                if (FCheckingType == "IsComplete")
                {
                    QueryType = "CreateByQuery";
                }
                basetable = KeysTable + "QueryCond";
                #endregion

                #region BuildCondition
                #region KeyInstance
                CONDTYPE = dwForeignKeyList["TForeignKey"].ToString().Trim();
                if (FPrimaryKeyTable == "KeyInstance")
                {
                    #region KeysTable
                    if (dwThis.Table.Columns.Contains("KeyInstanceTable"))
                    {
                        KeysTable = dwThis["KeyInstanceTable"].ToString().Trim();
                    }
                    if (dwThis.Table.Columns.Contains("SKeyInstanceTable"))
                    {
                        KeysTable = dwThis["SKeyInstanceTable"].ToString().Trim();
                    }

                    if (ForeignKey == "FK110_GoodsMasterKeyRelation_KeyInstance")
                    {
                        KeysTable = dwThis["KeyInstanceTable"].ToString().Trim();
                    }
                    if (ForeignKey == "FK112_GoodsMasterKeyRelation_KeyInstance")
                    {
                        KeysTable = dwThis["MKeyInstanceTable"].ToString().Trim();
                    }
                    if (ForeignKey == "FK114_GoodsMasterKeyRelation_KeyInstance")
                    {
                        KeysTable = dwThis["SKeyInstanceTable"].ToString().Trim();
                    }
                    #endregion
                    #region  _KeyInstanceQueryCond
                    basetable = KeysTable + "QueryCond";
                    if (CONDTYPE.Contains("_KeyInstance_"))
                    {
                        CONDTYPE = CONDTYPE.Replace("_KeyInstance_", "_" + KeysTable + "_");
                    }
                    else
                    {
                        CONDTYPE = "TX_" + KeysTable;
                    }
                    #endregion
                    blConditions = !SUBSTATUS.Contains(KeysTable + "Complete;");
                    DtQueryCond = KeysTable;
                }
                #endregion
                #endregion

                if (SUBSTATUS.Contains(KeysTable + "Complete"))
                {
                    QueryType = "QueryOnly";
                }
                #region Collect the paramaters
                dicSource["TargetKeyList"] = TargetKeyList;
                dicSource["SourceKeyList"] = SourceKeyList;
                dicSource["blConditions"] = blConditions;
                dicSource["DtQueryCond"] = DtQueryCond;
                dicSource["QueryType"] = QueryType;
                dicSource["basetable"] = basetable;
                dicSource["QueryCond"] = CONDTYPE;
                #endregion
            }
            catch (Exception ex)
            {
                throw;
            }
            return dicSource;
        }
        public bool ValidateRecord(ExDataRow dwThis)
        {
            string InstanceID = "";
            string GDKEY = "";
            string TBName = dwThis.Table.TableName;
            string SUBSTATUS = dwThis.SUBSTATUS;
            try
            {
                if (dwThis.Table.Columns.Contains("INSTANCEID"))
                {
                    InstanceID = dwThis.INSTANCEID.Trim();
                    if (InstanceID == "")
                        return false;
                    if (dwThis.Table.Columns.Contains("GDKEY"))
                    {
                        GDKEY = dwThis.Item["GDKEY"].ToString().Trim();
                        if (GDKEY == "1@2=1"
                            || GDKEY == ""
                            )
                        {
                            return false;
                        }
                    }
                    if (!SUBSTATUS.Contains("CheckGeneralComplete;"))
                    {
                        if (!CheckGeneral(dwThis.Item))
                        {
                            return false;
                        }
                    }
                    if (dwThis.ValidateGoodsMasterKeyRelation)
                    {
                        if (TBName == TBName
                            && !SUBSTATUS.Contains("GoodsMasterKeyRelationComplete;"))
                            return false;
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return true;
        }
        public bool CheckGeneral(DataRow dwThis)
        {
            Dictionary<string, object> dicSource = new Dictionary<string, object>();
            DataRow dwForeignKey = null;
            string FKCheckGeneral = string.Format("FK999_" + dwThis.Table.TableName + "_General");
            var query = from dwForeignkeyList in SetGlobal.FOREIGNKEYLIST.AsEnumerable()
                        where dwForeignkeyList["FOREIGNKEY"].ToString().Trim() == FKCheckGeneral
                        select dwForeignkeyList;
            foreach (DataRow dwTemp in query)
            {
                dwForeignKey = dwTemp;
            }
            try
            {
                dicSource = BuildKeyPair(dicSource, dwForeignKey, dwThis);
                if ((bool)dicSource["blConditions"])
                {
                    string SUBSTATUS = dwThis["SUBSTATUS"].ToString().Trim();
                    dwThis["SUBSTATUS"] = SUBSTATUS + "CheckGeneralComplete;";
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return (bool)dicSource["blConditions"];
        }
        public bool CheckKeyInstanceTable(DataRow dwSource, string Reason)
        {

            string KeyInstanceTable = "";
            if (dwSource.Table.Columns.Contains("KeyInstanceTable"))
            {

                KeyInstanceTable = dwSource["KeyInstanceTable"].ToString().Trim();
            }
            if (dwSource.Table.Columns.Contains("SKeyInstanceTable"))
            {
                KeyInstanceTable = dwSource["SKeyInstanceTable"].ToString().Trim();
            }
            if (KeyInstanceTable != "")
            {
                return true;
            }
            if (Reason.Contains("_" + KeyInstanceTable + "_"))
            {
                return true;
            }
            if (KeyInstanceTable != "")
            {
                return true;
            }
            return false;
        }
        public void CheckForeignKey(MessageEx This_Message)
        {
            try
            {
                #region Variable
                Dictionary<string, object> dicSource = new Dictionary<string, object>();
                Fluent.MenuItem sender;
                DataRow dwForeignKey = null;
                string JobID = This_Message.JobID;
                string Reason = JobID.Replace("OnCheck", "");

                string basetable = "";
                DataRow dwThis = null;// ActiveDataRow;
                var query = from dwForeignkeyList in SetGlobal.FOREIGNKEYLIST.AsEnumerable()
                            where dwForeignkeyList["ForeignKey"].ToString().Trim() == Reason
                            select dwForeignkeyList;
                foreach (DataRow dwTemp in query)
                {
                    dwForeignKey = dwTemp;
                }
                if (dwForeignKey == null)
                    return;
                string FYInstanceTable = dwForeignKey["YInstanceTable"].ToString().Trim();
                string SUBSTATUS = dwThis["SUBSTATUS"].ToString().Trim();
                string QueryCond = dwForeignKey["TForeignKey"].ToString().Trim();
                DataSet DataSetEvent = new DataSet();
                Queue TargetKeyList = new Queue();
                Queue SourceKeyList = new Queue();
                string DtQueryCond = "";
                string QueryType = "";
                bool blConditions = false;
                #endregion
                #region KeyInstanceTable
                if (FYInstanceTable == "Y")
                {
                    if (!CheckKeyInstanceTable(dwThis, Reason))
                    {
                        sender = new Fluent.MenuItem();
                        sender.Name = "OnThisPass";
                        //ActivateMenuItem(sender, null);
                        return;
                    }
                }
                #endregion
                dicSource = BuildKeyPair(dicSource, dwForeignKey, dwThis);
                blConditions = (bool)dicSource["blConditions"];
                DtQueryCond = (string)dicSource["DtQueryCond"];
                SourceKeyList = (Queue)dicSource["SourceKeyList"];
                TargetKeyList = (Queue)dicSource["TargetKeyList"];
                QueryType = (string)dicSource["QueryType"];
                basetable = (string)dicSource["basetable"];
                QueryCond = (string)dicSource["QueryCond"];
                #region Pass/Fail
                if (blConditions)//Conditions)
                {
                    sender = new Fluent.MenuItem();
                    sender.Name = "OnThisFail";
                    DataRow m_ActiveDataRow = null;
                    DataRow dwBaseQuery = DataAccessService.Instance.MapDataRow(QueryType, QueryCond, basetable, null, m_ActiveDataRow, SourceKeyList, TargetKeyList);
                    dwBaseQuery["REASON1"] = Reason;
                    DataSet setExchange = new DataSet();
                    setExchange = (DataSet)DataAccessService.Instance.ImportDataTable(setExchange, dwBaseQuery);
                    setExchange.AcceptChanges();
                    sender.Tag = setExchange;
                    //ActivateMenuItem(sender, null);
                }
                else
                {
                    sender = new Fluent.MenuItem();
                    sender.Name = "OnThisPass";
                    //ActivateMenuItem(sender, null);
                    DataRow m_ActiveDataRow = null;
                    if (Reason.StartsWith("FK999_"))
                    {
                        m_ActiveDataRow["STATUS"] = "Complete";
                        m_ActiveDataRow.AcceptChanges();
                        string InstanceID = m_ActiveDataRow["INSTANCEID"].ToString().Trim();
                        if (InstanceID == "")
                        {
                            sender = new Fluent.MenuItem();
                            sender.Name = "OnCreateByQuery";
                            //ActivateMenuItem(sender, null);
                        }
                    }
                }
                #endregion
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
        public ExDataRow OnNewRecord(string SM, string KEYDEFTYPE, string GOODSTYPEKEY, string GTKRY, string KEYINSTANCETABLE)
        {
            DataRow dwNew = null;
            ExDataRow rowNew = null;
            try
            {
                dwNew = SetGlobal.Tables[KEYINSTANCETABLE].NewRow();
                dwNew["INSTANCEID"] = Guid.NewGuid().ToString().ToUpper();
                dwNew["SM"] = SM;
                dwNew["KEYDEFTYPE"] = KEYDEFTYPE;
                dwNew["GTPRE"] = GOODSTYPEKEY;
                dwNew["GTKRY"] = GTKRY;
                if (dwNew.Table.Columns.Contains("GDKEY"))
                {
                    dwNew["GDKEY"] = "1@2=1";
                }
                DataSet setEvent = new DataSet();
                GenerateGoodsMasterKeyRelation(dwNew);
                MessageEx msg = new MessageEx();
                msg.JobID = "OnSaveRecord";
                setEvent = (DataSet)DataAccessService.Instance.ImportDataTable(setEvent, dwNew);
                msg.setEvent = setEvent;
                DataSet setResult = DataAccessService.Instance.QueryData(msg);
                foreach (DataRow dwTemp in setResult.Tables[0].Rows)
                {
                    rowNew =GetExDataRow(dwTemp, true, false);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            return rowNew;
        }

        public virtual DataSet getSet2Create(string addional = "", string CheckingType = "IsComplete")
        {
            ExDataRow dwThis = this;
            DataSet setReturn = new DataSet();
            DataRow[] dwForeignKeyLists;
            string TBName = dwThis.Table.TableName;
            string expression;
            DataSet setResult = null;
            DataSet set2Query = new DataSet();
            List<string> KeyList = new List<string>();
            List<string> TKeyList = new List<string>();
            string TargetTable = "";
            Queue queuetable2create = new Queue();
            DataSet set2Create = dwThis.Set2Create;
            try
            {
                expression = "TABLENAME='" + TBName + "'  and TARGETTABLE<>'" + TBName + "'  and TYPE='ForeignKey' and CheckingType='" + CheckingType + "' " + addional;
                dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                foreach (DataRow dwForeignKey in dwForeignKeyLists)
                {
                    set2Query = GetQueryCondByForeignKey(ref KeyList, ref TKeyList, ref TargetTable, dwForeignKey, dwThis.Item, CheckingType);
                    if (dwThis.IsTBCreated(TargetTable))
                    {
                        continue;
                    }
                    dwThis.AddSet2Create(TargetTable, null, false);
                    if (TargetTable == "GoodsMasterProperty"
                         && !ValidateRecord(dwThis))
                    {
                        continue;
                    }
                    setResult = QueryAndCreateData(set2Query, dwThis.Item);
                    foreach (DataTable tbTemp in setResult.Tables)
                    {
                        dwThis.AddSet2Create(TargetTable, tbTemp, false);
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return setReturn;
        }

        public virtual DataSet getSet4Reference(string TBName = "", string addional = "")
        {
            ExDataRow dwThis = this;
            ExDataSet setReturn = new ExDataSet();
            DataRow[] dwForeignKeyLists;
            if (TBName == "")
            {
                TBName = dwThis.Table.TableName;
            }
            string expression;
            DataSet set2Query = new DataSet();
            DataSet setResult;
            List<string> KeyList = new List<string>();
            List<string> TKeyList = new List<string>();
            string TargetTable = "";
            string CheckingType = "";
            try
            {
                expression = "TBNAME='" + TBName + "'  and TTTABLE<>'" + TBName + "' and TYPE='ForeignKey' " + addional;
                dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                foreach (DataRow dwForeignKey in dwForeignKeyLists)
                {
                    CheckingType = dwForeignKey["CHECKINGTYPE"].ToString().Trim();
                    set2Query =GetQueryCondByForeignKey(ref KeyList, ref TKeyList, ref TargetTable, dwForeignKey, dwThis.Item, CheckingType);
                    setResult = QueryAndCreateData(set2Query, dwThis.Item);
                    if (CheckingType == "IsNull")
                    {
                        dwThis.Set4Reference.Merge(setResult);
                    }
                    else
                    {
                        if (setResult.Tables[TargetTable].Rows.Count > 0)
                        {
                            dwThis.AddSet2Create(TargetTable, setResult.Tables[TargetTable], true);
                        }
                        else
                        {
                            dwThis.AddSet2Create(TargetTable, setResult.Tables[TargetTable], false);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return setReturn;
        }

        public DataSet getSet5KeyDef(string addiona = "")
        {
            ExDataRow dwThis = this;
            ExDataSet setReturn = new ExDataSet();
            DataSet setResult = new DataSet();
            Queue table5KeyDef = new Queue();
            table5KeyDef.Enqueue("GoodsTypeQueryCond");
            table5KeyDef.Enqueue("GoodsTypeKeyDefQueryCond");
            table5KeyDef.Enqueue("GoodsTypePropertyDefQueryCond");
            table5KeyDef.Enqueue("GoodsTypeKeyDefRelationQueryCond");
            table5KeyDef.Enqueue("GoodsTypeAssemblePointDefQueryCond");
            try
            {

                DataSet set2Query = new DataSet();
                DataRow dwQueryCond = null;
                string TBName = "GoodsTypeKeyDefQueryCond";
                while (table5KeyDef.Count > 0)
                {
                    TBName = (string)table5KeyDef.Dequeue();
                    set2Query = new DataSet();
                    set2Query.DataSetName = TBName;
                    dwQueryCond = DataAccessService.Instance.MapDataRow("QueryOnly", "IX_GoodsTypeKeyDef", TBName, null, dwThis.Item, null, null);
                    if (TBName == "GoodsTypeQueryCond")
                    {
                        dwQueryCond["CONDTYPE"] = "IX_GoodsType";
                    }
                    set2Query = (DataSet)DataAccessService.Instance.ImportDataTable(set2Query, dwQueryCond);
                    setResult = QueryAndCreateData(set2Query, dwThis.Item);
                    setReturn.Merge(setResult);
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public virtual DataSet GetQueryCondByForeignKey(ref List<string> KeyList, ref List<string> TKeyList, ref string TargetTable,
DataRow dwForeignKey, DataRow dwReference, string CheckingType = "IsNull")
        {
            string Key = "";
            string TKey = "";
            string QueryType = "QueryOnly";
            string CONDTYPE = "";
            string ForeignKey = "";
            DataRow dwQueryCond = null;
            string TBQueryCond = "";
            DataSet set2Query = new DataSet();
            string TBName = dwReference.Table.TableName;
            bool blKeyInstance = false;
            try
            {
                TargetTable = dwForeignKey["TARGETTABLE"].ToString().Trim();
                ForeignKey = dwForeignKey["FOREIGNKEY"].ToString().Trim();
                switch (TargetTable)
                {
                    case "SKeyInstanceTable":
                        TargetTable = dwReference["SKEYINSTANCETABLE"].ToString().Trim();
                        blKeyInstance = true;
                        break;
                    case "MKeyInstanceTable":
                        TargetTable = dwReference["MKEYINSTANCETABLE"].ToString().Trim();
                        blKeyInstance = true;
                        break;
                    case "TKeyInstanceTable":
                        TargetTable = dwReference["KEYINSTANCETABLE"].ToString().Trim();
                        blKeyInstance = true;
                        break;
                    case "KeyInstanceTable":
                        TargetTable = dwReference["KEYINSTANCETABLE"].ToString().Trim();
                        blKeyInstance = true;
                        break;
                    default:
                        break;
                }
                TBQueryCond = TargetTable + "QueryCond";
                CONDTYPE = dwForeignKey["TFOREIGNKEY"].ToString().Trim();
                if (blKeyInstance)
                {
                    if (CONDTYPE.Contains("_KeyInstance"))
                    {
                        CONDTYPE = CONDTYPE.Replace("_KeyInstance", "_" + TargetTable);
                    }
                    else
                    {
                        CONDTYPE = "TX_" + TargetTable;
                    }
                }
                QueryType = "QueryOnly";
                if (CheckingType == "IsComplete")
                {
                    QueryType = "CreateByQuery";
                }
                dwQueryCond = SetQuery.Tables[TBQueryCond].NewRow();
                DataAccessService.Instance.MapDataRow(ref dwQueryCond, dwReference, true);
                dwQueryCond["QUERYTYPE"] = QueryType;
                dwQueryCond["CONDTYPE"] = CONDTYPE;
                if (QueryType == "CreateByQuery")
                {
                    DataAccessService.Instance.ImportDataTable(ref set2Query, dwReference);
                }
                string KeyI = "";
                for (int i = 0; i < 10; i++)
                {
                    KeyI = "TKEY" + i.ToString();
                    TKey = dwForeignKey[KeyI].ToString().Trim();
                    TKeyList.Add(TKey);
                    KeyI = "KEY" + i.ToString();
                    Key = dwForeignKey[KeyI].ToString().Trim();
                    KeyList.Add(Key);
                    if (TKey != "" && Key != "")
                    {
                        if (TKey == "KEYINSTANCETABLE")
                        {
                            if (ForeignKey == "IX_GoodsTypeKeyDef_Table"
                                || ForeignKey == "IX_GoodsMasterKeyRelation_Key"
                                || ForeignKey == "FK100_GoodsMasterKeyRelation_MainKeyDef"
                                )
                            {
                                dwQueryCond[TKey] = dwReference[Key];
                            }
                            else
                            {
                                dwQueryCond[TKey] = TBName;
                            }
                            continue;
                        }
                        if (
                            dwQueryCond.Table.Columns.Contains(TKey)
                            && dwReference.Table.Columns.Contains(Key)
                        )
                        {
                            dwQueryCond[TKey] = dwReference[Key];
                        }
                    }
                }
                if (TargetTable == "GoodsMasterProperty")
                {
                    dwQueryCond["KEYINSTANCETABLE"] = TBName;
                    dwQueryCond["SGDKEY"] = dwReference["GDKEY"];
                }
                //need to check BaseTable
                dwQueryCond["FKEYINSTANCETABLE"] = TBName;
                DataAccessService.Instance.ImportDataTable(ref set2Query, dwQueryCond);
                set2Query.DataSetName = TBQueryCond;
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {

            }
            return set2Query;
        }
        public virtual bool CheckingSet2Create(bool IsCreate)
        {

            try
            {
                ExDataRow dwThis = this;
                DataSet setEvent = new DataSet();
                DataSet set2Create = dwThis.Set2Create; 
                if (dwThis.IsOnRunSelectedRecord)
                    return false;
                //If all the table or record is created, then start to validate them
                //and, if the table is goodsmasterproperty, it will tell the caller to load the table created.
                foreach (Table2Create t2cx in dwThis.Table2CreateList)
                {
                    string TBName = t2cx.TBName;
                    setEvent = new DataSet();
                    if (!set2Create.Tables.Contains(TBName))
                    {
                        continue;
                    }
                    if (set2Create.Tables[TBName].Rows.Count == 0)
                    {
                        continue;
                    }
                    setEvent.Merge(set2Create.Tables[TBName]);
                    DocumentManagement.Instance.SendJobForProcessing(setEvent, null, "Edit", false);
                }
                dwThis.IsOnRunSelectedRecord = true;
            }
            catch (Exception ex)
            {
                throw;
            }
            return true; ;
        }
        public void BuildSet4Reference()
        {
            DataSet setResult = new DataSet();
            setResult = getSet4Reference();
            CheckingSet2Create(true);
        }
        public void BuildSet4Reference(string tbName)
        {
            getSet4Reference(tbName);            
        }
        public virtual DataSet getSet4Reference(string tbName)
        {
            ExDataRow dwThis = this;
            ExDataSet setReturn = new ExDataSet();
            DataRow[] dwForeignKeyLists;
            string TBName = dwThis.Table.TableName;
            string expression;
            DataSet set2Query = new DataSet();
            DataSet setResult;
            List<string> KeyList = new List<string>();
            List<string> TKeyList = new List<string>();
            string TargetTable = "";
            string CheckingType = "";
            try
            {
                if (SetGlobal.Tables[tbName].Rows.Count > 0)
                {
                    return null;
                }
                expression = "TBNAME='" + TBName + "'  and TTTABLE<>'" + TBName + "' and TYPE='ForeignKey' " + " and TARGETTABLE='" + tbName + "' ";
                dwForeignKeyLists = SetGlobal.FOREIGNKEYLIST.Select(expression);
                foreach (DataRow dwForeignKey in dwForeignKeyLists)
                {
                    CheckingType = dwForeignKey["CHECKINGTYPE"].ToString().Trim();
                    set2Query = GetQueryCondByForeignKey(ref KeyList, ref TKeyList, ref TargetTable, dwForeignKey, dwThis.Item, CheckingType);
                    setResult = QueryAndCreateData(set2Query, dwThis.Item);
                    if (CheckingType == "IsNull")
                    {
                        SetGlobal.Merge(setResult);
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
            return setReturn;
        }
        public void BuildSet5Property()
        {
            try
            {
                ExDataRow dwThis = this;
                DataSet setEvent = new DataSet();
                DataSet set2Create = dwThis.Set2Create;
                DataTable tbGoodsMasterProperty = set2Create.Tables["GoodsMasterProperty"];
                if (tbGoodsMasterProperty == null)
                    return;
                SLBC doc = (SLBC)DocumentManagement.Instance.FindDocumentByAddress("EditGoodsMasterProperty", "EditGoodsMasterProperty");
                ExDataRow rowProperty = null;
                if (tbGoodsMasterProperty.Rows.Count == 0)
                    return;
                foreach (DataRow dwGoodsMasterProperty in tbGoodsMasterProperty.Rows)
                {
                    rowProperty = GetExDataRow(dwGoodsMasterProperty, true, false);
                    if (rowProperty.Set2Create.Tables.Count == 0)
                    {
                        rowProperty.LoadLifeData(5);
                    }
                    dwThis.Set5Property.Merge(rowProperty.Set2Create);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void BuildSet5Property(string tbName)
        {
            try
            {
                ExDataRow dwThis = this;
                DataSet setEvent = new DataSet();
                DataSet set2Create = dwThis.Set2Create;
                DataTable tbGoodsMasterProperty = set2Create.Tables["GoodsMasterProperty"];
                if (tbGoodsMasterProperty == null)
                    return;
                ExDataRow rowProperty = null;
                if (tbGoodsMasterProperty.Rows.Count == 0)
                    return;
                foreach (DataRow dwGoodsMasterProperty in tbGoodsMasterProperty.Rows)
                {
                    rowProperty = GetExDataRow(dwGoodsMasterProperty, true, false);
                    if (rowProperty.Item["SKEYINSTANCETABLE"].ToString().Trim() != tbName)
                        continue;
                    if (rowProperty.Set2Create.Tables.Count == 0)
                    {
                        rowProperty.LoadLifeData(5);
                    }
                    dwThis.Set5Property.Merge(rowProperty.Set2Create);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void BuildSet5KeyDef()
        {
            try
            {
                ExDataRow dwThis = this;
                DataSet setReturn = new DataSet();
                setReturn = getSet5KeyDef();
                foreach (DataTable tbTemp in setReturn.Tables)
                {
                    MergeDataList(dwThis.INSTANCEID, tbTemp, "Set5KeyDef");
                }
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
        public bool LoadLifeData(int level = 5)
        {
            bool IsComplete = true;
            ExDataRow row = this;
            try
            {
                switch (level)
                {
                    case 1:
                        BuildSet2Create(true);
                        break;
                    case 2:
                        BuildSet4Reference();
                        BuildSet2Create(true);
                        break;
                    case 4:
                        //BuildSet5KeyDef();
                        //BuildSet4Reference();
                        getSet2Create("", "IsComplete");
                        BuildSet5Property();
                        break;
                    case 5:
                        getSet2Create("", "IsComplete");
                        break;
                    case 3:
                    default:
                        BuildSet5KeyDef();
                        BuildSet4Reference();
                        BuildSet2Create(true);
                        break;
                }

            }
            catch (Exception ex)
            {
                throw;
            }
            return IsComplete;
        }

    }
}